<?php

/**
 * Description of ThingsController
 *
 * @author NE
 */
class Backend_ThingsController extends RCMS_Core_BaseController {

	protected $_languageId;

	protected $_languageName;

	protected $_browsePictures;

	protected $_browseFiles;

    public function init()
    {
        parent::init();
        $this->_checkLogin(array('downloadfile'));
        $this->_model = new Default_Model_ThingsModel();

		$this->_languageId = $this->_session->langId;
		$this->_languageName = strtolower($this->_languageId);

		if($this->_languageName==""){
			$this->_browsePictures  = 'swf-upload-browse-pictures.png';
			$this->_browseFiles = 'swf-browse-files.png';
		}else{
			$this->_browsePictures = 'swf-browse-pictures'."-".$this->_languageName.".png";
			$this->_browseFiles = 'swf-browse-files'."-".$this->_languageName.".png";
			if(!file_exists('system/js/swfupload/'.$this->_browsePictures)){
				$this->_browsePictures  = 'swf-browse-pictures.png';
			}

			if(!file_exists('system/js/swfupload/'.$this->_browseFiles)){
				$this->_browseFiles = 'swf-browse-files.png';
			}

		}

    }
    
    /**
     * This function loads template for upload image, video or others file.
     * @return void
     */
    public function uploadthingsAction()
    {
		$this->view->browsePictures = $this->_browsePictures;
		$this->view->browseFiles = $this->_browseFiles;

		/*swf-upload-browse-pictures-french.png
		swf-upload-browse-pictures-french
		*/
//		Zend_Debug::d($this->view->browsePictures );
		//Zend_Debug::d($this->view->browseFiles );
        $this->_helper->getHelper('layout')->disableLayout();
        $this->view->listFolders = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images);
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

    /**
     * This function is load template for removethings.
     * @return void
     */
    public function removethingsAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();

        $pathImages = $this->_config->website->website->path . $this->_config->website->website->images;
        $pathFiles = $this->_config->website->website->path . $this->_config->website->website->downloads;      
        $folder = '';
        $messageImages = '';
        $messageFiles = '';
        $messageVideos = '';
        $resultImages = array('delete'=> 0, 'exist' => array());
        $resultFiles = array('delete'=> 0, 'exist' => array());
        $resultVideos = array('delete'=> 0, 'exist' => array());        

        if($this->getRequest()->isPost())
        {
            //get variables
            $folder = $this->getRequest()->getParam('adminuploadselectfolder');
            $images = $this->getRequest()->getParam('images');
            $videos = $this->getRequest()->getParam('videos');
            $files = $this->getRequest()->getParam('files');

            //remove images
            if(!empty($images) && is_array($images) && $folder != '' && is_dir($pathImages . $folder))
            {
                $images = array_keys($images);
                $resultImages = $this->_deleteImages($images, $folder);
            }

            //remove files
            if(!empty($files) && is_array($files) && is_dir($pathFiles))
            {
                $files = array_keys($files);
                $resultFiles = $this->_deleteFiles($files, $folder, $pathFiles);
            }

            //remove video
            if(!empty($videos) && is_array($videos) && is_dir($pathImages . $folder . '/video/'))
            {
                $videos = array_keys($videos);
                $resultVideos = $this->_deleteFiles($videos, $folder, $pathImages . $folder . '/video/');
            }       
			            
            //generate message
            if($resultImages['delete'] > 0)
            {
                $messageImages .= '<p align="left">' . $resultImages['delete'] . ' picture' . ($resultImages['delete'] == 1 ?'':'s') . ' removed.</p>';
            }
            $messageImages .= $this->_generateMessageForRemoveThings($resultImages['exist']);

            if($resultFiles['delete'] > 0)
            {
                $messageFiles .= '<p align="left">' . $resultFiles['delete'] . ' file' . ($resultFiles['delete'] == 1 ?'':'s') . ' removed.</p>';
            }
            $messageFiles .= $this->_generateMessageForRemoveThings($resultFiles['exist']);

            if($resultVideos['delete'] > 0)
            {
                $messageVideos .= '<p align="left">' . $resultVideos['delete'] . ' video' . ($resultVideos['delete'] == 1 ?'':'s') . ' removed.</p>';
            }
            $messageVideos .= $this->_generateMessageForRemoveThings($resultVideos['exist']);

        }

        //if folder is empty then delete this folder
        $result = $this->_deleteFolderOrGetContent($pathImages, $folder);        
        
        $this->view->images = $result['images'];
        $this->view->listVideoFiles = $result['videos'];        
        $this->view->selectFolder = $result['folder'];
		//excluding languages files
		$filesToSort = RCMS_Tools_FilesystemTools::scanDir($pathFiles);
		$sortedFiles = array();
		if(!empty ($filesToSort)) {
			foreach ($filesToSort as $fileName) {
				if(strpos($fileName, '.lng')) {
					continue;
				}
				$sortedFiles[] = $fileName;
			}
		}
        $this->view->downloadFiles = $sortedFiles; //RCMS_Tools_FilesystemTools::scanDir($pathFiles);
        $this->view->listFolders = RCMS_Tools_FilesystemTools::scanDir($pathImages);
        $this->view->messageImages = $messageImages;
        $this->view->messageFiles = $messageFiles;
        $this->view->messageVideos = $messageVideos;
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

    /**
     * This function is generate message for removethings
     * @param array $array
     * @return string
     */
    private function _generateMessageForRemoveThings($array)
    {
        if(!empty($array) && is_array($array))
        {
            $message = '<p>Can not be removed:</p>';
            $message.= '<ul style="list-style-type: none;">';

            foreach ($array as $name => $arrayOverlaps)
            {
                $countOverlap = count($arrayOverlaps);

                if($countOverlap === 1)
                {
                    $message .= '<li><p align="left">' . $name . ((intval($arrayOverlaps[0]['page_id']) > 0 )?' <a target="_blank" href="' . $this->view->websiteUrl . $arrayOverlaps[0]['page_url'] . '.html">used here</a>.':' used static container.') . '</p></li>';
                }
                else
                {
                    if($countOverlap > 3)
                    {
                        $message .= '<li><p align="left">' . $name .
                        ((intval($arrayOverlaps[0]['page_id']) > 0)?' <a target="_blank" href="' . $this->view->websiteUrl . $arrayOverlaps[0]['page_url'] . '.html">used here</a>,':' used static container,') .
                        ((intval($arrayOverlaps[1]['page_id']) > 0)?' <a target="_blank" href="' . $this->view->websiteUrl . $arrayOverlaps[1]['page_url'] . '.html">used here</a>,':' used static container,') .
                        ((intval($arrayOverlaps[2]['page_id']) > 0)?' <a target="_blank" href="' . $this->view->websiteUrl . $arrayOverlaps[2]['page_url'] . '.html">used here</a>':' used static container') .
                        ' ... (' . $countOverlap. ')</p></li>';
                    }
                    else
                    {
                        $message .= '<li><p align="left">' . $name;
                        $i = 0;

                        foreach ($arrayOverlaps as $value)
                        {
                            $i++;
                            if(intval($value['page_id'])> 0)
                            {
                                $message .= ' <a target="_blank" href="' . $this->view->websiteUrl . $value['page_url'] . '.html">used here</a>';
                            }
                            else
                            {
                                $message .= ' used static container';
                            }

                            if($countOverlap === $i)
                            {
                                $message .= '.';
                            }
                            else
                            {
                                $message .= ',';
                            }
                        }
                        $message .= '</p></li>';
                    }
                }
            }
            return $message . '</ul>';
        }
        else
        {
            return '';
        }
    }

    /**
     * This function returns count of deleted pictures and count of pictures which are still in use.
     * @param array $images
     * @param string $folder
     * @return array
     */
    private function _deleteImages($images, $folder)
    {
        $path = $this->_config->website->website->path . $this->_config->website->website->images;
        $delete = 0;
        $exist = array();

        foreach ($images as $image) {
            $isExisted = $this->_model->selectContentIdByValueLike($image);

            if (empty($isExisted)) {
                $flagOriginal = RCMS_Tools_FilesystemTools::deleteFile($path . $folder . '/original/' . $image);
                $flagSmall = RCMS_Tools_FilesystemTools::deleteFile($path . $folder . '/small/' . $image);
                $flagMedium = RCMS_Tools_FilesystemTools::deleteFile($path . $folder . '/medium/' . $image);
                $flagLarge = RCMS_Tools_FilesystemTools::deleteFile($path . $folder . '/large/' . $image);
                
                if (is_file($path.$folder.'/crop/'.$image)) {
                    RCMS_Tools_FilesystemTools::deleteFile($path.$folder.'/crop/'.$image);
                }
                if (is_file($path.$folder.'/thumbnails/'.$image)) {
                    RCMS_Tools_FilesystemTools::deleteFile($path.$folder.'/thumbnails/'.$image);
                }

                if ($flagOriginal && $flagSmall && $flagMedium && $flagLarge) {
                    $delete++;
                }
            } else {
                $exist[$image] = $isExisted;
            }
        }
        if (is_file($path.$folder.'/'.$folder.'.xml')) {
            RCMS_Tools_FilesystemTools::deleteFile($path.$folder.'/'.$folder.'.xml');
        }

        return array('delete' => $delete, 'exist' => $exist);
    }

    /**
     * This function returns count of deleted files and count of files which are still in use.
     * @param array $files
     * @param string $folder
     * @param string $path
     * @return array
     */
    private function _deleteFiles($files, $folder, $path)
    {        
        $delete = 0;
        $exist = array();

        foreach ($files as $file)
        {
            $isExisted = $this->_model->selectContentIdByValueLike($file);

            if(empty($isExisted))
            {
                $flag = RCMS_Tools_FilesystemTools::deleteFile($path . $file);

                if($flag)
                {
                    $delete++;
                }
            }
            else
            {
                $exist[$file] = $isExisted;
            }
        }

        return array('delete' => $delete, 'exist' => $exist);
    }

    /**
     * This function deletes folder if folder is empty and returns array(images,videos) for content.
     * @param string $path
     * @param string $folder
     * @return array
     */
    private function _deleteFolderOrGetContent($path, $folder)
    {
        if($folder != '' && is_dir($path . $folder))
        {
            $isEmptyImages = RCMS_Tools_FilesystemTools::scanDir($path . $folder . '/original/');
            $isEmptyVideos = RCMS_Tools_FilesystemTools::scanDir($path . $folder . '/video/');
            if(empty($isEmptyImages) && empty($isEmptyVideos))
            {
                RCMS_Tools_FilesystemTools::rmDir($path . $folder . '/small/');
                RCMS_Tools_FilesystemTools::rmDir($path . $folder . '/medium/');
                RCMS_Tools_FilesystemTools::rmDir($path . $folder . '/large/');
                RCMS_Tools_FilesystemTools::rmDir($path . $folder . '/original/');
                RCMS_Tools_FilesystemTools::rmDir($path . $folder . '/video/');
                RCMS_Tools_FilesystemTools::rmDir($path . $folder . '/crop/');
                RCMS_Tools_FilesystemTools::rmDir($path . $folder . '/thumbnails/');
                RCMS_Tools_FilesystemTools::rmDir($path . $folder);
                return array('folder' => '', 'images' => array(), 'videos' => array());
            }
            else
            {
                $images = RCMS_Tools_FilesystemTools::scanDir($path . $folder . '/small/');
                $videos = RCMS_Tools_FilesystemTools::scanDir($path . $folder . '/video/');
                return array('folder' => $folder, 'images' => $images, 'videos' => $videos);
            }
        }

        return array('folder' => '', 'images' => array(), 'videos' => array());        
    }

	public function downloadfileAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$fileData = RCMS_Tools_Tools::decryptString($this->getRequest()->getParam('file'));
		$exploded = explode('.', $fileData);
		$pageId = $exploded[0];
		$fileName = str_replace($pageId . '.', '', $fileData);
		$page = new RCMS_Object_Page_Page($pageId);
		if($page->getProtected()) {
			if($this->_session->isLogged || $this->_session->memberLogged) {
				$fileLocation = $this->getWebSiteUrl() . 'downloads/' . $fileName;
				header("Content-type: application/force-download");
				header("Content-Transfer-Encoding: Binary");
				header("Content-length: " . filesize($fileLocation));
				header("Content-disposition: attachment; filename=" . basename($fileName) . "");
				readfile($fileLocation);
			}
			else {
				$this->_session->memberDownloadError = 'Please login to download this file';
				$this->_redirect($this->getWebSiteUrl(), array('exit' => true));
			}
		}
	}

}
